if (window.location.hash && window.location.hash == '#_=_') {
  // WTH Facebook?
  delete window.location.hash;
}

var hie = [];
var ids2names = {};
var host = 'http://kawal-pemilu.appspot.com';

function set_hie(depth, parent, opt_dontpush, opt_next) {
  hie.length = depth + 1;
  hie[depth] = parent;

  if (depth == 4) {
    display_tps(parent);
  } else {
    display_aggregate(parent, depth, opt_next);
  }

  var s = '<a href="javascript:set_hie(0, 0)">Nasional</a>';
  for (var i = 1; i < hie.length; i++) {
    s += ' &raquo; <a href="javascript:set_hie(' + i + ', ' + hie[i] + ')">' + ids2names[hie[i]] + '</a>';
  }
  $('#hie').html(s);
  $('#hie2').html(s);
  var ht = '0';
  for (var i = 1; i <= depth; i++) {
    ht = ht+'.'+hie[i];
  }
  if (!opt_dontpush) {
    history.pushState(null, null, '#'+ht);
    ga('send', 'screenview', {
	  'screenName': window.location.hash
	});
  }
}

function prefix_padd(num, cnt) {
  num = num + '';
  while (num.length < cnt) num = '0' + num;
  return num;
}

function image_filename(p, t, h) {
  return prefix_padd(p, 7) + prefix_padd(t, 3) + prefix_padd(h, 2);
}

function get(id) {
  var x = $('#' + id).val();
  if (!$.isNumeric(x)) throw alert('Fail: ' + id + ' is not numeric -> ' + $('#' + id).val());
  return parseInt(x);
}

function update_sum(tps_no) {
  var prabowo = $('#input1_' + tps_no).val() || 0;
  var jokowi = $('#input2_' + tps_no).val() || 0;
  $('#input3_' + tps_no).val(parseInt(prabowo) + parseInt(jokowi));
}

function input_box(parent, tps_no) {
  return 'Data belum dimasukkan.';
}

function gen_values(parent, reported_by, tps_no, prabowo, jokowi, valid, invalid, fbid) {
  var err = '';
  if (reported_by) {
    err += '<br/>Error reported';
  } else {
	var hash = (location.hash.length>0) ? location.hash.substr(1) : "";
	err += "<br/><a target=\"_blank\" href=\"https://docs.google.com/forms/d/1YT78OME0woe3MA2bjhLoaWFU3GRB1XKAC0WSTrS3Ap0/viewform?entry.523444839=" + hash
	       + "&entry.1914184921=" + parent +
	       "&entry.1875556460=" + ids2names[hie[3]] + "&entry.711131508=" + ids2names[hie[4]] + "&entry.875394862=" + tps_no + "&entry.475186929=\">Laporkan kesalahan</a>";
  }
  return '<table>' +
    '<tr><td>Prabowo:<td id="tps_id1_' + tps_no + '">' + prabowo +
    '<tr><td>Jokowi:<td id="tps_id2_' + tps_no + '">' + jokowi +
    '<tr><td>Suara sah:<td id="tps_id3_' + tps_no + '">' + valid +
    '<tr><td>Tidak sah:<td id="tps_id4_' + tps_no + '">' + invalid +
//    '<tr><td>Entered by: &nbsp; <td id="input_box_'+ tps_no +'" align=center>' +
//      '<span class="fbguy">' + fbid + '</span>' +
    '<tr><th colspan=2>' + err +
  '</table>';
}

function display_tps(parent) {
  $('#msg_status').html('Fetching ...');
  $('#msg_status2').html('Fetching ...');
  $.ajax(host + '/api/tps/' + parent, { cache: false }).done(function(data) {
    $('#msg_status').html('');
    $('#msg_status2').html('');
    var s = '<table border="1"><thead><tr>\
      <th width="50">TPS\
      <th width="175">C1 full scan\
      <th width="225">C1 snippet\
      <th width="200">Crowd-sourced Values\
    </thead><tbody>';
    var tps_pending = 0;
    for (var i = 0; i < data.length; i++) {
      var r = data[i];
      var tps_no = i + 1;
      var is_pending = !r[2] && !r[3] && !r[4] && !r[5];
      var has_scan = r[6];
      var has_error = (r[7] == '0') ? false : r[7];
      var entered_by = r[8];
      var num = image_filename(parent, tps_no, 4);
      if (is_pending && !tps_pending) tps_pending = tps_no;
      s += '<tr bgcolor=' + (has_error ? '#ffaaaa' : '') + '><th>#' + r[0] +
        '<td align=center>' +
        'Jika snippet di sebelah<br>kanan salah, anda bisa<br>melihat halaman lainnya<br>dari website KPU:<br><br>' +
          '<a href="http://scanc1.kpu.go.id/viewp.php?f=' + image_filename(parent, tps_no, 1) + '.jpg" target="_blank">Halaman 1</a><br/>' +
          '<a href="http://scanc1.kpu.go.id/viewp.php?f=' + image_filename(parent, tps_no, 2) + '.jpg" target="_blank">Halaman 2</a><br/>' +
          '<a href="http://scanc1.kpu.go.id/viewp.php?f=' + image_filename(parent, tps_no, 3) + '.jpg" target="_blank">Halaman 3</a><br/>' +
          '<a href="http://scanc1.kpu.go.id/viewp.php?f=' + image_filename(parent, tps_no, 4) + '.jpg" target="_blank">Halaman 4</a><br/>' +
        '<td><a href="http://scanc1.kpu.go.id/viewp.php?f=' + num +
          '.jpg" target="_blank"><div style="width: 200px; height: 300px; overflow: hidden;">' +
        '<img style="position: relative; left: -400px; top: -120px;" width="600" src="http://scanc1.kpu.go.id/viewp.php?f=' + num + '.jpg"></div></a>' +
        '<td align=center id="csval_'+ tps_no +'">' + (has_scan ? (is_pending ? input_box(parent, tps_no) :
          gen_values(parent, has_error, tps_no, r[2], r[3], r[4], r[5], entered_by)) : ' N / A ');
    }
    document.getElementById('tbl').innerHTML = s + '</tbody></table>';
//    resolve_fbguys();
    setTimeout(function () {
      $('#input1_' + tps_pending).focus();
      var el = $('#input1_' + tps_pending).position();
      if (el) $(window).scrollTop(el.top - 400);
    }, 100);
  });
}

function percent(rat) {
  if (isNaN(rat)) return '0.00';
  var p = Math.floor(rat * 10000);
  return Math.floor(p / 100) + '.' + prefix_padd(p % 100, 2);
}

function replace_char(s, index, ch) {
  return s.substr(0, index) + ch + s.substr(index + 1);
}

function format(number) {
  if (number == 0) return '0';
  var nres = '' + number;
  var res = '';
  for (var i =0; i< nres.length;i++) {
    if (i > 0 && i%3 == 0) {
      res = '.' + res;
    }
    res = nres[nres.length-i-1] + res;
  }
  return res;
}

function display_aggregate(parent, depth, opt_next) {
  $('#msg_status').html('Fetching ...');
  $('#msg_status2').html('Fetching ...');
  $.ajax(host + '/api/children/' + parent, {
    cache: false,
    data: {},
    dataType: "text", // expect back a text to sanitize errors.
    error: function (xhr, status, error) {
      console.log(status);
      console.error(error);
    },
    success: function( data_txt ) {
    // Bugs:
    var x = data_txt.indexOf("PALENGA'\"AN");
    if (x != -1) data_txt = replace_char(data_txt, x + 8, '\'');
    x = data_txt.indexOf("RA'\"AS");
    if (x != -1) data_txt = replace_char(data_txt, x + 3, '\'');
    var data = JSON.parse(data_txt);
    var wda1 = depth < 3;

    $('#msg_status').html('');
    $('#msg_status2').html('');
    var s = '<table class="aggregate"><thead><tr bgcolor="#DDDDDD">\
      <th width="40">No\
      <th width="225">Tempat\
      <th width="120" colspan="2">Prabowo-Hatta' +
      (wda1 ? '<th width="120" colspan="2">Prabowo-Hatta<br/>(DA1)' : '')      +
      '<th width="120" colspan="2">Jokowi-JK' +
      (wda1 ? '<th width="120" colspan="2">Jokowi-JK<br/>(DA1)' : '') +
      '<th width="70">Suara sah\
      <th width="70">Tidak sah\
      <th width="70">TPS Error\
      <th width="120" colspan="2">TPS Diproses\
      <th width="200" colspan="2">Tersedia/Total TPS'+
      (wda1 ? '<th width="70">DA1%' : '') + 
    '</thead><tbody>';

    var total = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
    for (var i = 0; i < data.length; i++) {
      var r = data[i];
      var prabowo_count = r[2];
      var jokowi_count = r[3];
      var valid_count = r[4];
      var invalid_count = r[5];
      var errors_count = r[6];
      var entered_count = r[7];
      var pending_count = r[8];
      var tps_count = r[9];
      var prabowo_percent = percent(prabowo_count / (prabowo_count + jokowi_count)) + '%';
      var jokowi_percent = percent(jokowi_count / (prabowo_count + jokowi_count)) + '%';
      for (var j = 2; j <= 9; j++) total[j] += r[j];

      ids2names[r[0]] = r[1];
      var sort_of_done_entered = (percent(entered_count / tps_count) >= 99) ? 'bgcolor=lightgreen' : '';
      var sort_of_done_available = (percent(pending_count / tps_count) >= 99) ? 'bgcolor=lightgreen' : '';
      s += '<tr><td align=center>' + (i + 1) +
        '<td><a href="javascript:set_hie(' + (depth + 1) + ',' + r[0] +')">' + r[1] + '</a>' +
        '<td align=right width=60>' + format(prabowo_count) +
        '<td align=right ' + (prabowo_count > jokowi_count ? "bgcolor=lightgreen" : "") + '>' + prabowo_percent +
        (wda1 ? '<td align=right id="da_pb_c_' + i + '"></td><td align=right id="da_pb_p_' + i + '"></td>' : '') +
        '<td align=right width=60>' + format(jokowi_count) +
        '<td align=right ' + (prabowo_count < jokowi_count ? "bgcolor=lightgreen" : "") + '>' + jokowi_percent +
        (wda1 ? '<td align=right id="da_jk_c_' + i + '"></td><td align=right id="da_jk_p_' + i + '"></td>' : '') +
        '<td align=right>' + format(valid_count) +
        '<td align=right>' + format(invalid_count) +
        '<td align=right>' + format(errors_count) +
        '<td align=right width=60>' + format(entered_count) +
        '<td align=right '+sort_of_done_entered+'>' + percent(entered_count / pending_count) + '%' +
        '<td align=right width=120>' + format(pending_count) + ' / ' + format(tps_count) +
        '<td align=right '+sort_of_done_available+'>' + percent(pending_count / tps_count) + '%' +
        (wda1 ? '<td align=right id="da_p_' + i + '"></td>' : '');
    }

    var prabowo_count = total[2];
    var jokowi_count = total[3];
    var valid_count = total[4];
    var invalid_count = total[5];
    var errors_count = total[6];
    var entered_count = total[7];
    var pending_count = total[8];
    var tps_count = total[9];
    var prabowo_percent = percent(prabowo_count / (prabowo_count + jokowi_count)) + '%';
    var jokowi_percent = percent(jokowi_count / (prabowo_count + jokowi_count)) + '%';
    s += '<tr bgcolor="#DDDDDD"><td>&nbsp;' +
      '<th align="right">TOTAL: &nbsp; ' +
      '<td align=right width=60>' + format(prabowo_count) +
      '<td align=right ' + (prabowo_count > jokowi_count ? "bgcolor=lightgreen" : "") + '>' + prabowo_percent +
              (wda1 ? '<td align=right id="da_pb_ct"><td align=right id="da_pb_pt">' : '') +
      '<td align=right width=60>' + format(jokowi_count) +
      '<td align=right ' + (prabowo_count < jokowi_count ? "bgcolor=lightgreen" : "") + '>' + jokowi_percent +
              (wda1 ? '<td align=right id="da_jk_ct"><td align=right id="da_jk_pt">' : '') +
      '<td align=right>' + format(valid_count) +
      '<td align=right>' + format(invalid_count) +
      '<td align=right>' + format(errors_count) +
      '<td align=right width=60 bgcolor=lightgreen>' + format(entered_count) +
      '<td align=right bgcolor=lightgreen>' + percent(entered_count / pending_count) + '%' +
      '<td align=right width=100>' + format(pending_count) + ' / ' + format(tps_count) +
      '<td align=right>' + percent(pending_count / tps_count) + '%' +
               (wda1 ? '<td align=right id="da_pt"></td>' : '') +
     '</tbody></table>';

    if (opt_next && opt_next()) {
       // Do nothing
    } else { 
      $('#tbl').html(s);
      if (wda1) {
        dapath = '0';
        if (depth >= 1) {
          dapath = hie[1];
        }
        if (depth >= 2) {
          dapath = dapath + '.' + hie[2];
        }
        $.ajax(host + '/da1/' + dapath, {
          cache: false,
          data: {},
          dataType: "text", // expect back a text to sanitize errors.
          error: function (xhr, status, error) {
            console.log(status);
            console.error(error);
          },
          success: function( data_txt ) {
            var data = JSON.parse(data_txt);
            var dd = (depth == 0) ? 2 : 1;
            for (i = dd; i < data.length - 1; i++) {
              var row = data[i];
              if (row[3].charAt(5)!='N'){
                var pbc = row[3].split(';'); 
                document.getElementById('da_pb_c_'+(i-dd)).innerText = pbc[1].replace(",", ".");
                document.getElementById('da_pb_p_'+(i-dd)).innerText = pbc[4] + "%";
                var jkc = row[6].split(';'); 
                document.getElementById('da_jk_c_'+(i-dd)).innerText = jkc[1].replace(",", ".");
                document.getElementById('da_jk_p_'+(i-dd)).innerText = jkc[4] + "%";
                document.getElementById('da_p_'+(i-dd)).innerText = row[10].split(';')[5].replace("_", "");
              }
            }
            var row = data[data.length-1];
            if (row[3].charAt(5)!='N'){
                var pbc = row[3].split(';'); 
                document.getElementById('da_pb_ct').innerText = pbc[1].replace(",", ".");
                document.getElementById('da_pb_pt').innerText = pbc[4] + "%";
                var jkc = row[6].split(';'); 
                document.getElementById('da_jk_ct').innerText = jkc[1].replace(",", ".");
                document.getElementById('da_jk_pt').innerText = jkc[4] + "%";
                document.getElementById('da_pt').innerText = row[10].split(';')[5].replace("_", "");
              }
          }
        });
      }
    }
  }});
}

function updatePos(opt_pos) {
  if (location.hash == "") {
    set_hie(0, 0);
    return false;
  }
  var hies = location.hash.substr(1).split('.');
  if (opt_pos >= hies.length) {
    return false;
  }
  for (var i = opt_pos; i+1 < hies.length; i++) {
    if (hie.length <= i || hie[i] != hies[i-0]) {
      set_hie(i, hies[opt_pos], true, function() { return updatePos(i+1);});
      return true;
    }
  }
  set_hie(hies.length-1, hies[hies.length-1], true, function() { return false;});
  return true;
}

function reload() {
 nest = location.hash != "";
  if (nest) {
   updatePos(0);
	ga('send', 'screenview', {
	  'screenName': window.location.hash
	});
  } else 
    set_hie(0, 0);
}

$(function () {
  reload();
})

window.onhashchange = reload;